package com.dxl.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;

import java.util.Date;

/**
 * @author dxl
 * @date 2020/11/14 23:08
 */
public class JwtUtil {

    /**
     * 过期时间10分钟
     */
    private static final long EXPIRE_TIME = 60 * 60 * 1000;
    /**
     * jwt 密钥
     */
    private static final String SECRET = "jwt_secret";

    /**
     * 生成签名，10分钟后过期
     * @param userId
     * @return
     */
    public static String sign(Long userId) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            return JWT.create()
                    // 将 userDTO id 保存到 token 里面
                    .withClaim("userId", userId)
                    // 10分钟后token过期
                    .withExpiresAt(date)
                    // token 的密钥
                    .sign(algorithm);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 根据token获取userId
     * @param token
     * @return
     */
    public static Long getUserId(String token) {
        try {
            Long userId = JWT.decode(token).getClaim("userId").asLong();
            System.out.println(userId);
            return userId;
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static Boolean  checkSign(String token) {
        try {
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            throw new RuntimeException("无效签名");
        }catch (TokenExpiredException e) {
            e.printStackTrace();
            throw new RuntimeException("token过期");
        }catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            throw new RuntimeException("token算法不一致");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token无效");
        }
        return false;
    }
}